package com.yunxun.coinmessage.controller;

import com.yunxun.coinmessage.entity.Administrator;
import com.yunxun.coinmessage.templatedata.MsgResult;
import com.yunxun.coinmessage.service.AdministratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class AdministratorController {
    @Autowired
    AdministratorService administratorService;
    @RequestMapping("/addAdministrator")
    @ResponseBody
    public MsgResult addAdministrator(Administrator administrator){
        Integer a= administratorService.add(administrator);
        MsgResult msgResult=new MsgResult();
        if(a!=null){
           msgResult.setStatus(true);
           msgResult.setMsg("添加管理员成功");
        }else {
            msgResult.setStatus(false);
            msgResult.setMsg("添加管理员失败");
        }
        return msgResult;
    }
     //打开添加管理员的窗口
    @RequestMapping("/openAdministrator")
    public String openAdministrator(){
        return "administrator-add";
    }
    @RequestMapping("/loginAdmin")
    @ResponseBody
    public ModelAndView loginAdmin(String aname, String apassword){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Administrator administrator=administratorService.queryAdministrator(aname,apassword);
        if(administrator!=null){
            HttpSession session =request.getSession();
            session.setMaxInactiveInterval(60*60*24);
            session.setAttribute("administrator",administrator);
            return new ModelAndView("redirect:/coinadmin");
        }
         ModelAndView mav=new ModelAndView("redirect:/openLogin","msg","用户名或密码错误");
        return mav;
    }
    //打开登录管理员的窗口
    @RequestMapping("/openLogin")
    public  String openLogin(Model model,boolean flag,String msg){
        model.addAttribute("flag",flag);
        model.addAttribute("msg",msg);
        return "login";
    }
    @RequestMapping("/prevent-inline")
    public  String openPreventInline(){
        return "prevent-inline";
    }
}
